package net.wanho.employ.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.wanho.employ.dto.AdminDTO;
import net.wanho.employ.entity.Admin;
import net.wanho.employ.exception.UsernameExistsException;
import net.wanho.employ.mapper.AdminMapper;
import net.wanho.employ.service.AdminService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2024-03-25 15:45
 * Description：<描述>
 */
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Override
    public PageInfo<Admin> query(int pageNum, int pageSize, AdminDTO adminDTO) {
        PageHelper.startPage(pageNum, pageSize);

        List<Admin> list = adminMapper.query(adminDTO);

       return new PageInfo<>(list);
    }

    @Override
    public void add(Admin admin) {
        /**
         * 判断用户名是否存在
         */
        Admin a = adminMapper.selectByUsername(admin.getUsername());
        if (!ObjectUtils.isEmpty(a)){
            throw new UsernameExistsException("用户名已存在！");
        }

        /**
         * 添加用户
         */
        admin.setAdminid(IdUtil.simpleUUID());
        admin.setPassword(MD5.create().digestHex("123"));
        admin.setAddtime(new Date());

        adminMapper.insert(admin);
    }

    @Override
    public Admin findById(String adminid) {
        return adminMapper.selectById(adminid);
    }

    @Override
    public void modify(Admin admin) {
        /**
         * 判断用户名是否存在
         */
        Admin a = adminMapper.selectByUsername(admin.getUsername());
        if (!ObjectUtils.isEmpty(a)){
            throw new UsernameExistsException("用户名已存在！");
        }

        adminMapper.update(admin);
    }
}
